# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import *

from eqportal.qsync.models import *


def register(request, template_name):
    form = {}
    if request.method == "POST":
        try:
            User.objects.get(username = request["username"])
        except ObjectDoesNotExist:
            new_user = User.objects.create_user(request["username"], request["email"], request["passwd"])
            new_userinfo = UserInfo(user = new_user, guild =
                                    Guild.objects.get_or_create(name = request["guildname"],
                                                                defaults = {'name': request["guildname"]})[0])
            new_user.save()
            new_userinfo.save()
            return HttpResponseRedirect("/login")
        form["username"] = request["username"]
        form["email"] = request["email"]
        form["passwd"] = request["passwd"]
        form["guildname"] = request["guildname"]        
    return render_to_response(template_name, {"form": form})

settings = {'quest_per_page': 20}
def show_all_quests(request, sort_by, page):
    quests_per_page = 20
    page_num = 0
    if page:
        page_num = int(page)
    quests = Quest.objects.order_by(sort_by)[page_num * quests_per_page:(page_num + 1) * quests_per_page]
    return render_to_response("quest_list.html", {'settings': settings, 'quests': quests, 'sort_by': sort_by, 'page': page_num})

@login_required()
def show_grouped_quests(request, group_by, params):
    def _add_to(s, v):
        parts = v.split('-')
        if len(parts) > 1:
            [s.append(x) for x in range(int(parts[0]), int(parts[1]) + 1)]
        else:
            s.append(v)
    param_set = []
    [_add_to(param_set, v) for v in params.split(',')]
    querier = {'id': lambda x, y: x.filter(id__in = y),
              'level': lambda x, y: x.filter(level__in = y),
              }    
    
    quests = querier[group_by](Quest.objects, param_set).order_by(group_by)
    class _quest_info:
        def __init__(self, q, attr, user):
            self.quest = q
            self.info = getattr(q, attr)
            self.already_joined = bool(q.questrequest_set.filter(user=user))
            self.guild_joined = bool(q.questrequest_set.filter(user__userinfo__guild__name=user.guild.name))

    this_user = UserInfo.objects.get(user=request.user)
    return render_to_response("quest_list_grouped.html", {'settings': settings, 'quests': [_quest_info(q, group_by, this_user) for q in quests], 'group_by': group_by, 'user': {'name': request.user.username, 'guildname': this_user.guild.name}})

def show_one_quest(request, quest_id):
    #quest = Quest.objects.get(pk = quest_id)
    quest = get_object_or_404(Quest, pk = quest_id)
    joined_users = quest.questrequest_set.all()
    return render_to_response("quest.html", {'settings': settings, 'quest': quest, 'joined_users': joined_users})

def search_quests_by_prefix(request, prefix="empty"):
#    return HttpResponse("hello, search world! %s" % prefix)    
    #quests = Quest.objects.filter(name__istartswith=prefix)
    quests = Quest.objects.filter(name__icontains=prefix)
    return render_to_response("quest_search_by_name.html", {'settings': settings, 'quests': quests, 'search_text': prefix})

@login_required
def join_to_quest(request, quest_id):
    qr = QuestRequest(quest = Quest.objects.get(pk=quest_id), user = request.user)
    qr.save()
    return HttpResponse("hello!")

@login_required
def unjoin_to_quest(request, quest_id):
    qr = QuestRequest.objects.filter(user=request.user).get(quest=quest_id)
    qr.delete()
    return HttpResponse("hello!")

@login_required
def complete_quest(request, quest_id):
    return unjoin_to_quest(request, quest_id)
#    qr = QuestRequest(quest = Quest.objects.get(pk=quest_id), user = request.user)
#    qr.save()
#    return HttpResponse("hello!")

@login_required
def quests_by_guild(request):
    this_user = UserInfo.objects.get(user=request.user)
    quests = Quest.objects.filter(questrequest__user__userinfo__guild=this_user.guild)
    return render_to_response("quest_search_by_name.html", {'settings': settings, 'quests': quests, 'search_text': "123", 'user': {'name': request.user.username, 'guildname': this_user.guild.name}})

